package service;

import entity.AccessToken;
import org.json.JSONObject;
import util.Request;

import java.io.InputStream;
import java.util.Map;

public class Authorize {
    static InputStream in= Authorize.class.getClassLoader().getResourceAsStream("wx-config.xml");
    static Map<String,String> Xmlmap= WxServiceImpl.parseRequest(in);
    private static final String AUTHORIZE_URL=Xmlmap.get("authorizeUrl");
    private static final String AUTHORIZE_URL_2=Xmlmap.get("authorizeUrl2");
    private static final String REFRESH_TOKEN=Xmlmap.get("refreshToken");
    private static final String APPID=Xmlmap.get("appidTest");
    private static final String SECRT=Xmlmap.get("secrtTest");
    private static final String REDIRECT_URL= Xmlmap.get("redirectUrl");
    private static final String AUTH_USER_INFO=Xmlmap.get("authUserInfo");

    private static AccessToken at;
    private static AccessToken rt;

    public static String getAuthorizeUrl(){
        return AUTHORIZE_URL.replace("APPID",APPID).replace("URL",REDIRECT_URL);
    }
    //    2592000
    private static void getToken(String code){
        String url=AUTHORIZE_URL_2.replace("APPID",APPID).replace("SECRET",SECRT).replace("CODE",code);
        String tokenstr= Request.get(url);
        JSONObject jsonObject=new JSONObject(tokenstr);
        String token=jsonObject.getString("access_token");
        int expires=jsonObject.getInt("expires_in");
        String reToken=jsonObject.getString("refresh_token");
        at=new AccessToken(token,expires);
        rt=new AccessToken(reToken,2592000);
    }
    private static void getReToken(){
        String url=REFRESH_TOKEN.replace("APPID",APPID).replace("REFRESH_TOKEN",rt.getToken());
        String tokenstr= Request.get(url);
        JSONObject jsonObject=new JSONObject(tokenstr);
        String token=jsonObject.getString("access_token");
        int expires=jsonObject.getInt("expires_in");
        at=new AccessToken(token,expires);
    }

    public static String getAccessToken(String code){
        if(at==null||at.isExpires()){
            if (rt==null||rt.isExpires()){
                getToken(code);
            }
            else{
                getReToken();
            }
        }
        return at.getToken();
    }

    public static String getUserInfo(String code,String openId){
        String url=AUTH_USER_INFO.replace("ACCESS_TOKEN",getAccessToken(code)).replace("OPENID",openId);
        return Request.get(url);
    }
}
